import com.im30.jenkins.pipeline.models.ArcDiff

// TODO 应该从 Credential 里取，但 ConduitCredentials 是自定义的，还不支持
def applyPath(String DIFF_ID, ArcDiff diff, CONDUIT_URL = "https://phab.gotoim30.com/", CONDUIT_TOKEN = 'api-r6unxhmakxszfenshetmsjh7u3nz') {
    sh 'echo -e "## Getting base rev for diff"'

    if (diff != null) {
        sh "git reset --hard ${diff.baseCommit}"
    } else {
        sh """
            BASE_GIT_COMMIT=\$(echo '{\"diff_id\":${DIFF_ID}}' | arc call-conduit differential.getdiff --conduit-token ${CONDUIT_TOKEN} --conduit-uri ${CONDUIT_URL} | awk -v RS=',' -v FS=':' '/sourceControlBaseRevision/ {print \$2}' | tr -d '"')
            git reset --hard \$BASE_GIT_COMMIT
        """
    }

    sh 'echo -e "## Apply diff"'
    sh "arc patch --force --nobranch --no-ansi --diff ${DIFF_ID} --nocommit --conduit-token ${CONDUIT_TOKEN} --conduit-uri '${CONDUIT_URL}'"
}

def fetchArcDiff(String DIFF_ID, CONDUIT_URL = "https://phab.gotoim30.com/", CONDUIT_TOKEN = 'api-r6unxhmakxszfenshetmsjh7u3nz') {
    try {
        def filename = '.ci-diff.json'
        sh "echo '{\"diff_id\":${DIFF_ID}}' | arc call-conduit differential.getdiff --conduit-token ${CONDUIT_TOKEN} --conduit-uri ${CONDUIT_URL} > ${filename}"
        def diffJson = readJSON file: filename
        def revisionID = diffJson['response']['revisionID']
        def branch = diffJson['response']['branch']
        def baseCommit = diffJson['response']['sourceControlBaseRevision']
        sh "echo '{\"ids\":[${revisionID}]}' | arc call-conduit differential.query --conduit-token ${CONDUIT_TOKEN} --conduit-uri ${CONDUIT_URL} > ${filename}"
        def revisionJson = readJSON file: filename
        // TODO 暂时忽略 title 检测
        def title = revisionJson['response'][0]['title']

        sh "rm ${filename}"
        return new ArcDiff(title, revisionID, branch, baseCommit)
    } catch (err) {
        echo err.getMessage()
        return null
    }
}